package com.kermel.andromeda.clock.format;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.kermel.andromeda.data.settings.ClockSettings;
import com.kermel.common.util.StringUtils;

public class CurrentTimeFormatter {
    protected static final String FORMAT_HOURS_MILITARY = "HH";
    protected static final String FORMAT_HOURS_NORMAL = "hh";
    protected static final String FORMAT_MINUTES = "mm";
    protected static final String FORMAT_SECONDS = "ss";
    protected static final String FORMAT_AM_PM_MARKER = "aa";
    protected static final String DEFAULT_FORMAT = FORMAT_HOURS_MILITARY + ":" + FORMAT_MINUTES;
    protected static final String DELIMETER = ":";
    
    protected String formatPattern;
    
    private Calendar now;
    private SimpleDateFormat dateFormatter;
    private ClockSettings clockSettings;

    public CurrentTimeFormatter(ClockSettings clockSettings) {
        this.clockSettings = clockSettings;
        
        now = Calendar.getInstance();
        dateFormatter = new SimpleDateFormat(DEFAULT_FORMAT);
        updateFormatPatternWithClockSettings();
    }
    
    private void updateFormatPatternWithClockSettings() {
        String hoursFormat = buildHoursFormat();
        String secondsFormat = buildSecondsFormat();
        formatPattern = buildFormatPattern(hoursFormat, FORMAT_MINUTES, secondsFormat);
        dateFormatter.applyPattern(formatPattern);
    }
    
    protected String buildHoursFormat() {
        String hoursFormat = FORMAT_HOURS_NORMAL;
        
        if (clockSettings.isMilitaryTime())
            hoursFormat = FORMAT_HOURS_MILITARY;
        
        return hoursFormat;
    }
    
    protected String buildSecondsFormat() {
        String secondsFormat = null;
        
        if (clockSettings.isDisplaySeconds())
            secondsFormat = FORMAT_SECONDS;
        
        return secondsFormat;
    }
    
    protected String buildFormatPattern(String hoursFormat, String minutesFormat, String secondsFormat) {
        StringBuilder result = new StringBuilder(hoursFormat);
        
        result.append(DELIMETER).append(minutesFormat);
        
        if (secondsFormat != null)
            result.append(DELIMETER).append(secondsFormat);
        
        if (clockSettings.isMilitaryTime() == false)
            result.append(StringUtils.SPACE).append(FORMAT_AM_PM_MARKER);
        
        return result.toString();
    }
    
    public CharSequence formatTimeAsString(long currentTime) {
        now.setTimeInMillis(currentTime);
        
        updateFormatPatternWithClockSettings();
        
        CharSequence timeAsString = dateFormatter.format(now.getTime());
        return timeAsString;
    }
    
    public String getFormatPattern() {
        return formatPattern;
    }
}
